package com.zoshine.zzg.service;

import com.zoshine.zzg.base.BaseBean;
import com.zoshine.zzg.dao.BaseDao;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.util.idworker.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 抽象服务基础类
 *
 * @author 贾俊峰
 * @time 2017/7/11 20:05
 */
@Service
public abstract class BaseService<T extends BaseBean> {
    private BaseDao<T> baseDao;
    protected IdWorker<Long> baseIdWorker;

    @Autowired
    public void setBaseDao(BaseDao<T> baseDao) {
        this.baseDao = baseDao;
    }
    @Autowired
    public void setBaseIdWorker(IdWorker<Long> baseIdWorker) {
        this.baseIdWorker = baseIdWorker;
    }

    public T add(T t) {
        t.setId(baseIdWorker.createId());
        t.setCreateTime(new Date());
        t.setUpdateTime(new Date());
        baseDao.insert(t);
        return t;
    }

    public int del(T t) {
        return baseDao.delete(t);
    }

    public int del(Long id) {
        return baseDao.deleteByPrimaryKey(id);
    }

    public int del(List<T> list) {
        List<Long> idList = new ArrayList<>();
        for (T t : list) {
            idList.add(t.getId());
        }
        return baseDao.batchDelete(idList);
    }

    public int del(String idStr) {
        if (idStr == null || idStr.length() == 0) {
            throw new AppException(ErrorMessage.REQUEST_PARAM_CAN_NOT_NULL);
        }
        String[] idArr = idStr.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id : idArr) {
            try {
                Long l = Long.parseLong(id);
                idList.add(l);
            } catch (NumberFormatException ex) {
                throw new AppException(ErrorMessage.REQUEST_PARAM_TYPE_ERROR);
            }
        }
        if (idList.size() != 0) {
            return baseDao.batchDelete(idList);
        }
        return 0;
    }

    public int edit(T t) {
        t.setUpdateTime(new Date());
        return baseDao.update(t);
    }

    public T get(T t) {
        return baseDao.selectOne(t);
    }

    public T get(Long id) {
        return baseDao.selectByPrimaryKey(id);
    }

    public List<T> list(T t) {
        return baseDao.selectList(t);
    }

    public int add(List<T> list) {
        return baseDao.batchInsert(list);
    }
}
